<template>
	<view class="image-uploader">
		<view class="section-header">
			<view class="section-icon">📷</view>
			<text class="section-title">上传图片</text>
			<text class="section-required">*</text>
		</view>

		<!-- 图片列表 -->
		<!-- 图片列表 -->
		<view class="images-wrapper">
			<scroll-view class="images-container" scroll-x="true" show-scrollbar="false">
				<view class="images-content">
					<!-- 添加图片按钮 - 移到最左边 -->
					<view v-if="images.length < maxImages" class="add-image-btn" @click="chooseImage">
						<view class="add-icon">+</view>
						<text class="add-text">添加图片</text>
					</view>

					<!-- 已上传的图片 - 放在上传框右边 -->
					<view v-for="(image, index) in images" :key="index" class="image-item"
						:class="{ 'is-cover': image.url === coverImage }">
						<image :src="image.url" class="uploaded-image" mode="aspectFill" />

						<!-- 删除按钮 - 移到右上角 -->
						<view class="delete-btn-circle" @click="removeImage(index)">
							<text class="delete-icon">×</text>
						</view>

						<!-- 操作按钮 - 只保留封面按钮 -->
						<view class="image-actions">
							<view class="action-btn cover-btn" :class="{ 'is-cover': image.url === coverImage }"
								@click="setCover(image.url)">
								<text class="btn-text">{{ image.url === coverImage ? '封面' : '设为封面' }}</text>
							</view>
						</view>

						<!-- 封面标识 -->
						<view v-if="image.url === coverImage" class="cover-badge">
							<text class="cover-text">封面</text>
						</view>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 提示信息 -->
		<view class="upload-tips">
			<text class="tip-text">• 最多上传{{ maxImages }}张图片</text>
			<text class="tip-text">• 必须选择一张图片作为封面</text>
			<text class="tip-text">• 支持jpg、png格式，单张图片不超过5MB</text>
		</view>

		<!-- 加载状态 -->
		<view v-if="uploading" class="upload-loading">
			<view class="loading-spinner"></view>
			<text class="loading-text">上传中...</text>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, watch, defineEmits, defineProps } from 'vue'
	import { uploadFile } from '@/api/upload/upload'
	import type { PostImage } from '@/api/post/post'

	interface Props {
		maxImages ?: number
		modelValue ?: PostImage[]
		coverImage ?: string
	}

	interface Emits {
		(e : 'update:modelValue', value : PostImage[]) : void
		(e : 'update:coverImage', value : string) : void
	}

	const props = withDefaults(defineProps<Props>(), {
		maxImages: 9
	})

	const emit = defineEmits<Emits>()

	const images = ref<PostImage[]>(props.modelValue || [])
	const coverImage = ref<string>(props.coverImage || '')
	const uploading = ref(false)

	// 监听props变化
	watch(() => props.modelValue, (newVal) => {
		images.value = newVal || []
	}, { deep: true })

	watch(() => props.coverImage, (newVal) => {
		coverImage.value = newVal || ''
	})

	// 选择图片
	const chooseImage = () => {
		uni.chooseImage({
			count: props.maxImages - images.value.length,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				uploadImages(res.tempFilePaths)
			},
			fail: (err) => {
				console.error('选择图片失败:', err)
				uni.showToast({
					title: '选择图片失败',
					icon: 'none'
				})
			}
		})
	}

	// 上传图片
	// 上传图片
	const uploadImages = async (filePaths : string[]) => {
		uploading.value = true
		let successCount = 0

		try {
			for (const filePath of filePaths) {
				const response = await uploadFile(filePath)

				if (response.code === 200 && response.url) {
					const newImage : PostImage = {
						url: response.url,
						order: images.value.length + 1
					}

					images.value.push(newImage)
					successCount++

					// 如果是第一张图片，自动设为封面
					if (images.value.length === 1) {
						setCover(newImage.url)
					}
				} else {
					uni.showToast({
						title: '上传失败',
						icon: 'none'
					})
				}
			}

			// 显示上传成功提示
			if (successCount > 0) {
				uni.showToast({
					title: `成功上传${successCount}张图片`,
					icon: 'success',
					duration: 2000
				})
			}

			updateParent()
		} catch (error) {
			console.error('上传图片失败:', error)
			uni.showToast({
				title: '上传失败',
				icon: 'none'
			})
		} finally {
			uploading.value = false
		}
	}

	// 删除图片
	const removeImage = (index : number) => {
		const removedImage = images.value[index]
		images.value.splice(index, 1)

		// 重新排序
		images.value.forEach((img, idx) => {
			img.order = idx + 1
		})

		// 如果删除的是封面，重新设置封面
		if (removedImage.url === coverImage.value) {
			if (images.value.length > 0) {
				setCover(images.value[0].url)
			} else {
				coverImage.value = ''
				emit('update:coverImage', '')
			}
		}

		updateParent()
	}

	// 设置封面
	const setCover = (url : string) => {
		coverImage.value = url
		emit('update:coverImage', url)
	}

	// 更新父组件
	const updateParent = () => {
		emit('update:modelValue', images.value)
	}
</script>

<style lang="scss" scoped>
	.image-uploader {
		padding: 32rpx;
	}

	.section-header {
		display: flex;
		align-items: center;
		margin-bottom: 24rpx;

		.section-icon {
			font-size: 32rpx;
			margin-right: 16rpx;
		}

		.section-title {
			font-size: 32rpx;
			font-weight: 600;
			color: #1f2937;
		}

		.section-required {
			color: #ef4444;
			margin-left: 8rpx;
		}
	}

	.images-wrapper {
		margin-bottom: 24rpx;
	}

	.images-container {
		width: 100%;
		height: 320rpx;
		white-space: nowrap;
	}

	.images-content {
		display: flex;
		flex-direction: row;
		align-items: flex-start;
		gap: 16rpx;
		padding: 0 4rpx;
	}

	.add-image-btn {
		width: 280rpx;
		height: 280rpx;
		border: 2rpx dashed #d1d5db;
		border-radius: 16rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: #f9fafb;
		flex-shrink: 0;
		order: -1; // 确保上传按钮始终在最左边

		.add-icon {
			font-size: 60rpx;
			color: #9ca3af;
			margin-bottom: 12rpx;
		}

		.add-text {
			font-size: 28rpx;
			color: #6b7280;
		}
	}

	.image-item {
		position: relative;
		border-radius: 16rpx;
		overflow: hidden;
		border: 4rpx solid transparent;
		flex-shrink: 0;
		width: 280rpx;

		&.is-cover {
			border-color: #3b82f6;
		}
	}

	.uploaded-image {
		width: 280rpx;
		height: 280rpx;
		border-radius: 12rpx;
	}

	// 新增：圆形删除按钮样式
	.delete-btn-circle {
		position: absolute;
		top: 6rpx;
		right: 6rpx;
		width: 36rpx;
		height: 36rpx;
		border-radius: 50%;
		background: #ef4444;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.3);
		z-index: 10;

		.delete-icon {
			font-size: 24rpx;
			color: white;
			font-weight: bold;
			line-height: 1;
		}

		&:active {
			background: #dc2626;
			transform: scale(0.95);
		}
	}

	.image-actions {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		background: linear-gradient(transparent, rgba(0, 0, 0, 0.6));
		display: flex;
		justify-content: center;
		padding: 8rpx;
	}

	.action-btn {
		padding: 4rpx 10rpx;
		border-radius: 12rpx;
		backdrop-filter: blur(8rpx);
		border: 1rpx solid rgba(255, 255, 255, 0.2);
		transition: all 0.2s ease;

		.btn-text {
			font-size: 18rpx;
			color: white;
			font-weight: 500;
		}

		&:active {
			transform: scale(0.95);
		}
	}

	.cover-btn {
		background: rgba(59, 130, 246, 0.7);

		&.is-cover {
			background: rgba(34, 197, 94, 0.8);
			box-shadow: 0 2rpx 8rpx rgba(34, 197, 94, 0.3);
		}

		&:hover {
			background: rgba(59, 130, 246, 0.9);
		}
	}

	.cover-badge {
		position: absolute;
		top: 6rpx;
		left: 6rpx;
		background: linear-gradient(135deg, #3b82f6, #1d4ed8);
		padding: 2rpx 6rpx;
		border-radius: 8rpx;
		box-shadow: 0 2rpx 6rpx rgba(59, 130, 246, 0.4);
		border: 1rpx solid rgba(255, 255, 255, 0.3);

		.cover-text {
			font-size: 16rpx;
			color: white;
			font-weight: 600;
			letter-spacing: 0.5rpx;
		}
	}

	.upload-tips {
		padding: 16rpx;
		background: #f0f9ff;
		border-radius: 12rpx;
		margin-bottom: 24rpx;

		.tip-text {
			display: block;
			font-size: 24rpx;
			color: #0369a1;
			line-height: 1.5;
			margin-bottom: 4rpx;
		}
	}

	.upload-loading {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 32rpx;

		.loading-spinner {
			width: 32rpx;
			height: 32rpx;
			border: 3rpx solid #e5e7eb;
			border-top: 3rpx solid #3b82f6;
			border-radius: 50%;
			animation: spin 1s linear infinite;
			margin-right: 16rpx;
		}

		.loading-text {
			font-size: 28rpx;
			color: #6b7280;
		}
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}

		100% {
			transform: rotate(360deg);
		}
	}
</style>